let token = getToken();
let user = JSON.parse(window.localStorage.getItem("userInfo"));

const toRenderMessagesList = (arr) => {
  const messagesListNode = arr
    .map((i) => {
      const {
        createTime,
        message,
        status: { display },
        reMessage,
      } = i;
      // 在这里写样式
      return `<div class="message-item">
              <div>
                <span>时间:</span>
                <span>${createTime}</span>
              </div>
              <div>
                <span>状态:</span>
                <span>${display}</span>
              </div>
              ${
                display === "已处理" ? `
              <div>
                <span>回复:</span>
                <span>${reMessage}</span>
              </div>` : ''}
              <div>
                <span>留言:</span>
                <span>${message}</span>
              </div>
            </div>`;
    })
    .join("");

  $("#message_list").append(messagesListNode);
};

window.onload = () => {
  $.ajax({
    url: `${server}v1/api/message/${user.id}`,
    dataType: "json",
    type: "get",
    processData: false,
    headers: { "Content-Type": "application/json", token: token },
    success: function (res) {
      const { code, data } = res;
      if (code == 200) {
        toRenderMessagesList(data);
      } else {
        mui.alert(res.msg);
      }
    },
    error: function (err) {
      mui.alert("请求失败，请稍后重试");
    },
  });
};

$("#leaveMessage").click(function () {
  const feedBackVal = $("#textValue").val();
  if (!feedBackVal) {
    mui.alert(`请先进行留言`);
    return false;
  }
  const params = {
    message: feedBackVal,
  };
  $.ajax({
    url: `${server}v1/api/message/save/user/${user.id}`,
    data: JSON.stringify(params),
    dataType: "json",
    type: "post",
    processData: false,
    headers: { "Content-Type": "application/json", token: token },
    success: function (res) {
      if (res.code == 200) {
        mui.alert("添加成功!");
        setTimeout(() => {
          // location.href = "index2.html";
          window.onload()
        }, 1000);
      } else {
        mui.alert(res.msg);
      }
    },
    error: function (err) {
      mui.alert("留言失败，请稍后重试");
    },
  });
});
